package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    /**
     * 秒杀下单
     * @param voucherId
     * @return
     */
    public Result seckillVoucher(Long voucherId) {
        //获取秒杀优惠券相关信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        LocalDateTime beginTime = voucher.getBeginTime();
        LocalDateTime endTime = voucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();

        //先判断时间
        if (now.isAfter(endTime)){
            return Result.fail("秒杀已结束!");
        }
        if (now.isBefore(beginTime)){
            return Result.fail("秒杀活动还没开始!");
        }
        //判断库存是否充足
        if (voucher.getStock() < 1){
            return Result.fail("库存不足!");
        }
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();
        if (!success){
            return Result.fail("库存不足!!");
        }
        //成功，创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //代金券id
        voucherOrder.setVoucherId(voucherId);
        //用户id
        long userId = UserHolder.getUser().getId();
        voucherOrder.setUserId(userId);
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);

        //保存订单
        save(voucherOrder);

        return Result.ok(orderId);
    }
}
